/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.agilelang.fgl.parser;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import org.agilelang.object.WebClient;
import org.agilelang.object.WebServices;

/**
 *
 * @author Roderick
 */
public class WebServicesProcess extends Process {

    private WebServices webservices;
    private Class cls = null;
    private HashMap appwebclient;

    public WebServicesProcess() {
        webservices = new WebServices();
        appwebclient = new HashMap();
        try {
            cls = Class.forName("org.agilelang.object.WebServices");
        } catch (ClassNotFoundException ex) {
            error = "Error " + ex.toString();
        }
    }

    public boolean process(String aLine) {
        this.error = "";

        WebServices model;
        String name_model = this.setSingularize(aLine);
        if (this.isReservedWord(name_model.toLowerCase())) {
            this.error = "Error nombre es palabra reservada  : " + name_model;
            return false;
        }
        if (appwebclient.containsKey(name_model)) {
            model = (WebServices) appwebclient.get(name_model);
        } else {
            model = new WebServices();
            model.name = name_model;
            //model.table = this.setPluralizeNaked(name_model).toLowerCase();
        }
        Function function = Util.getFunction(aLine);

        if (function.name.equals("define")) {
            String[] param = Util.split(function.val, ",");
            for (int i = 0; i < param.length; i++) {
                String[] paramdel = Util.split(param[i], "=");
                String name = paramdel[0];
                String value = paramdel[1].substring(1, paramdel[1].length() - 1);
                if (Util.setField(cls, name, model, value)) {
                    appwebclient.put(model.name, model);
                } else {
                    this.error = "Error parametro de la funcion \"define\" no existe : " + name;
                    return false;
                }
            }
        }
        return true;
    }

    public List<WebServices> getListWebServices() {
        List<WebServices> listmodel = new ArrayList<>();
        SortedSet<String> sortedset = new TreeSet<>(appwebclient.keySet());
        Iterator<String> it = sortedset.iterator();
        while (it.hasNext()) {
            WebServices model = (WebServices) appwebclient.get(it.next());
            listmodel.add(model);
        }
        return listmodel;
    }
}
